import { ref, computed, provide, inject } from 'vue'
import { ethers } from 'ethers'
import { handleWeb3Error } from '../utils/error'
import { NETWORKS } from '../contracts/config'

export function useWeb3() {
  const provider = ref(null)
  const signer = ref(null)
  const account = ref('')
  const chainId = ref(null)
  const isConnected = ref(false)
  const isConnecting = ref(false)

  // 当前网络
  const currentNetwork = computed(() => {
    if (!chainId.value) return null
    return Object.values(NETWORKS).find(network => network.chainId === chainId.value)
  })
  // 连接钱包
  async function connect() {
    if (isConnecting.value) return
    isConnecting.value = true
    
    try {
      // 检查是否安装了 MetaMask
      if (!window.ethereum) {
        throw new Error('请安装 MetaMask')
      }

      // 请求账户连接
      const accounts = await window.ethereum.request({
        method: 'eth_requestAccounts'
      })
      console.log('accounts',accounts)
      
      // 设置 provider 和 signer
      let ethersProvider;
      
      // 检查是否是本地 Hardhat 网络
      const networkVersion = await window.ethereum.request({ method: 'net_version' });
      console.log('当前网络ID:', networkVersion);
      
      if (networkVersion === '31337') {
        // Hardhat 本地网络
        ethersProvider = new ethers.JsonRpcProvider('http://127.0.0.1:8545');
        console.log('连接到 Hardhat 本地网络');
      } else {
        // 其他网络使用 BrowserProvider
        ethersProvider = new ethers.BrowserProvider(window.ethereum);
        console.log('连接到 MetaMask 网络');
      }
      
      provider.value = ethersProvider;
      signer.value = await ethersProvider.getSigner();
      account.value = accounts[0];
      
      // 获取链 ID
      const network = await ethersProvider.getNetwork();
      chainId.value = Number(network.chainId);
      console.log('chainId:', chainId.value);
      
      isConnected.value = true;

      // 监听账户变化
      window.ethereum.on('accountsChanged', handleAccountsChanged)
      // 监听链变化
      window.ethereum.on('chainChanged', handleChainChanged)

    } catch (error) {
      console.error('Connection error:', error)
      handleWeb3Error(error)
      isConnected.value = false
      provider.value = null
      signer.value = null
    } finally {
      isConnecting.value = false
    }
  }

  // 断开连接
  function disconnect() {
    provider.value = null
    signer.value = null
    account.value = ''
    chainId.value = null
    isConnected.value = false

    // 移除事件监听
    if (window.ethereum) {
      window.ethereum.removeListener('accountsChanged', handleAccountsChanged)
      window.ethereum.removeListener('chainChanged', handleChainChanged)
    }
  }

  // 切换网络
  async function switchNetwork(networkId) {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: `0x${networkId.toString(16)}` }]
      })
    } catch (error) {
      handleWeb3Error(error)
    }
  }

  // 处理账户变化
  function handleAccountsChanged(accounts) {
    if (accounts.length === 0) {
      // 用户断开了钱包连接
      disconnect()
    } else {
      // 账户切换
      account.value = accounts[0]
    }
  }

  // 处理链变化
  function handleChainChanged(newChainId) {
    chainId.value = Number(newChainId)
    // 重新连接以更新 provider
    connect()
  }

  // 提供值
  provide('web3', {
    provider,
    signer,
    account,
    chainId,
    isConnected,
    isConnecting,
    connect,
    disconnect,
    switchNetwork,
    currentNetwork,
  });
}

// 创建一个函数来注入这些值
export function useInjectedWeb3() {
  const web3 = inject('web3');
  if (!web3) {
    throw new Error('useWeb3 must be used within a provider');
  }
  return web3;
}
